<template>
    <div>
        <div>
            <table-set :tableHeader="tableHeader" @headerSet="headerSet"></table-set>
            <div class="search-wrap fr">
                <table-search
                    ref="table-search"
                    :selectHead="selectHead"
                    @searchMethods="searchMethods"></table-search>
            </div>
            <orderStatistics :myInfo ='$store.state.user' :roleID='$store.state.user.role_id'/>
        </div>
        <el-table
            border
            :data="tableData"
            :height="tableHeight"
            v-loading="loading"
            @sort-change="tableSort"
            ref="check-fee"
            v-if="table_show"
        >
            <el-table-column
                show-overflow-tooltip
                label="ID"
                min-width="60"
                align="left"
                v-if="checked99"
            >
                <template slot-scope="scope">{{(scope.$index + 1) + (current_page - 1) * per_page}}</template>
            </el-table-column>
            <template v-for="(item, index) in tableHeader">
                <el-table-column
                    show-overflow-tooltip
                    :key="index"
                    v-if="item.prop == 'remind_time' && item.is_show"
                    :label="item.label"
                    :prop="item.prop"
                    min-width="160"
                    sortable='custom'
                    align="left"
                >
                    <template slot-scope="scope">
                        {{ getAuditorDate(scope.row )}}
                    </template>
                </el-table-column>
                <el-table-column
                    show-overflow-tooltip
                    :key="index"
                    v-if="item.prop == 'order_number' && item.is_show"
                    :label="item.label"
                    :prop="item.prop"
                    min-width="200"
                    align="left"
                    sortable='custom'
                ></el-table-column>
                <el-table-column
                    show-overflow-tooltip
                    :key="index"
                    v-if="item.prop == 'type' && item.is_show"
                    :label="item.label"
                    :prop="item.prop"
                    min-width="120"
                    align="left"
                    sortable='custom'

                ></el-table-column>
                <el-table-column
                    show-overflow-tooltip
                    :key="index"
                    v-if="item.prop == 'status' && item.is_show"
                    :label="item.label"
                    :prop="item.prop"
                    min-width="120"
                    align="left"
                    sortable='custom'
                ></el-table-column>
                <el-table-column
                    show-overflow-tooltip
                    :key="index"
                    v-if="item.prop == 'patent_name' && item.is_show"
                    :label="item.label"
                    :prop="item.prop"
                    min-width="150"
                    align="left"
                    sortable='custom'
                ></el-table-column>
                <el-table-column
                    show-overflow-tooltip
                    :key="index"
                    v-if="item.prop == 'agent_id' && item.is_show"
                    :label="item.label"
                    :prop="item.prop"
                    align="left"
                    sortable='custom'
                    min-width="90"
                >
                    <template slot-scope="scope">
                        {{scope.row.agent.name}}
                    </template>
                </el-table-column>
                <el-table-column
                    show-overflow-tooltip
                    :key="index"
                    v-if="item.prop == 'teacher_opinions_count' && item.is_show"
                    :label="item.label"
                    :prop="item.prop"
                    align="left"
                    min-width="120"
                    sortable='custom'
                ></el-table-column>
                <el-table-column
                    :key="index"
                    v-if="item.prop == 'student_review_file' && item.is_show"
                    :label="item.label"
                    :prop="item.prop"
                    align="left"
                    min-width="220"
                    sortable='custom'
                >
                    <template slot-scope="scope">
                        <div class="flie-hid">
                            <a v-for="(item, index) in scope.row.fileArr"
                                :key="index"
                                :href="baseUrl + '/api/download?path=' + item"
                                :download="item"
                                :title="item.split('/')[2]"
                                class="el-icon-tickets file_sh">
                            </a>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column
                    show-overflow-tooltip
                    :key="index"
                    v-if="item.prop == 'updated_at' && item.is_show"
                    :label="item.label"
                    :prop="item.prop"
                    align="left"
                    min-width="160"
                    sortable='custom'
                ></el-table-column>
            </template>
            <el-table-column
                label="操作"
                align="center"
                width="180"
                fixed="right"
                v-if="checked99"
            >
                <template slot-scope="scope">
					<el-button
                        :disabled="!scope.row.can_click"
                        type="primary"
                        size="small"
                        @click="auditorOrder(scope.row)"
                        v-no-more-click:3000>
                        审核
                    </el-button>
					<el-button
						:class="{'opinions-count': scope.row.noRead > 0}"
						:data-before="scope.row.noRead"
                        :disabled="!scope.row.teacher_opinions_count"
						size="small"
						@click="showAudito(scope.row, scope.$index)"
						v-no-more-click:3000>
						审核记录
					</el-button>
				</template>
            </el-table-column>
        </el-table>

        <!-- 审核记录弹窗 -->
		<el-dialog title="审核记录" :visible.sync="showAuditoRecording" center class="lookAuditRecord">

			<el-timeline>
				<el-timeline-item v-for="(item, index) in teacher_opinions" :key="index" :timestamp="item.created_at">
					<el-card>
						<h4 class="flex-line">
                            <span class="title">审核员：</span>
                            <span class="finish content">{{item.review_user}}<span v-if="item.from == '审核员'">(审核员)</span></span>
                            <Tooltip content="点我回复" class="fr" v-if="index == 0">
                                <i class="el-icon-chat-dot-round leaveWord ml5" @click="agentAnwser(item)"></i>
                            </Tooltip>
                        </h4>
                        <div class="flex-line">
                            <span class="title">审核意见：</span>
                            <span class="content clip">
                                <span>{{item.review_cn}}</span>
                            </span>
                        </div>
                        <div class="flex-line" v-if="item.money_cn">
                            <span class="title">扣款金额：</span>
                            <span class="content unfinish">{{item.money_cn}}元</span>
                        </div>
                        <div v-for="(agent, index) in item.agent_message" :key="index" class="pl15">
                            <h4 class="flex-line">
                                <span class="title">回复人：</span>
                                <span class="el-blue content">
                                    <span v-if="agent.review_user.indexOf('&&&学生留言') > -1">{{ agent.review_user.split('&&&')[0] }}(学生)</span>
                                    <span v-else-if="agent.review_user.indexOf('&&&审核员留言') > -1" class="finish">{{ agent.review_user.split('&&&')[0] }}(审核员)</span>
                                    <span v-else-if="agent.review_user.indexOf('&&&老师留言') > -1" class="finish">{{ agent.review_user.split('&&&')[0] }}</span>
                                    <span v-else>{{ agent.review_user }}</span>
                                    <span class="time">{{agent.created_at}}</span>
                                </span>
                            </h4>
                            <div class="flex-line">
                                <span class="title">回复内容：</span>
                                <span class="content">{{agent.review}}</span>
                            </div>
                        </div>
					</el-card>
				</el-timeline-item>
			</el-timeline>
		</el-dialog>

        <!-- 审核弹窗 -->
        <el-dialog title="审核订单" :visible.sync="dialogFormVisible" center @close='showAuditRecord'>
			<el-form :model="form" :rules="rules" ref="ruleForm">
				<el-form-item label="审核意见" prop="review">
					<el-input type="textarea" :rows="4" placeholder="请输入审核意见，通过无需输入。" v-model="form.review"></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button type="danger" @click="submitForm('ruleForm','no')"  v-no-more-click:3000>退 回</el-button>
				<el-button type="primary" @click="submitForm('ruleForm','yes')" :disabled='qualityFailed' v-no-more-click:3000>通 过</el-button>
			</div>
		</el-dialog>

        <pagination @paginationChange="pageChange" :total="total" v-if="search_end"></pagination>
        <!-- 代理人回复 -->
		<agent-anwser ref="agent-anwser" @refresh="refreshData"></agent-anwser>
    </div>
</template>

<script>
import pagination from '~/components/pagination'
import tableSet from '~/components/tableSet'
import orderStatistics from "~/components/orderStatistics"
import agentAnwser from '../order/dialogPage/agent-anwser'
import { getMyInfo } from "~/api/user";
import tableSearch from '~/components/tableSearch'
export default {
    components: {
        tableSet,
        pagination,
        orderStatistics,
        agentAnwser,
        tableSearch
    },
    data() {
        return {
            dialogFormVisible: false,
            showAuditoRecording: false,
            tableData: [],
            loading: false,
            baseUrl: global.baseurl,
            current_page: 1,
            table_show: true,
            per_page: 25,
            total: 0,
            form: {
                review: ''
            },
            checked99: true,
            selectHead: [
                {
                    label: '订单编号',
                    props: 'order_number',
                }, {
                    label: '专利类型',
                    props: 'type',
                }, {
                    label: '流程状态',
                    props: 'status',
                }, {
                    label: '拟申报专利名称',
                    props: 'patent_name',
                }, {
                    label: '代理人',
                    props: 'agent_id',
                }, {
                    label: '审核次数',
                    props: 'teacher_opinions_count',
                }, {
                    label: '修改时间',
                    props: 'updated_at',
                }
            ],
            teacher_opinions: [],
            rules: {
                review: [{
                    // required: true,
                    message: "请输入审批意见",
                    trigger: "blur"
                }]
            },
            search_end: true,
            tableHeader: [
                {
                    label: '等待审核时间(天)',
                    prop: 'remind_time',
                    is_show: true
                }, {
                    label: '订单编号',
                    prop: 'order_number',
                    is_show: true
                }, {
                    label: '专利类型',
                    prop: 'type',
                    is_show: true
                }, {
                    label: '流程状态',
                    prop: 'status',
                    is_show: true
                }, {
                    label: '拟申报专利名称',
                    prop: 'patent_name',
                    is_show: true
                }, {
                    label: '代理人',
                    prop: 'agent_id',
                    is_show: true
                }, {
                    label: '审核次数',
                    prop: 'teacher_opinions_count',
                    is_show: true
                }, {
                    label: '内容审核文件',
                    prop: 'student_review_file',
                    is_show: true
                }, {
                    label: '修改时间',
                    prop: 'updated_at',
                    is_show: true
                }
            ],
            sort_params: {},
            search_params: {},
            qualityFailed: false
        }
    },
    computed: {
        tableHeight() {
            let height = 1000
            if (process.client) {
                height = window.innerHeight - 202
            }
            return height
        },

    },

    created() {
        this.getTableData()
    },

    methods: {

        gwm() {
            //水印,非管理员要设置
            if (this.$store.state.user.role_id != 1
                && this.$route.path != '/admin/register'
                && this.$route.path != '/admin/personalCenter/dstribution'
                && this.$route.path != '/admin/personalCenter/myPurse'
                && this.$route.path != '/admin/activityList/activityConfig'
                && this.$route.path != '/admin/activityList/sysConfig'
                && this.$route.path !='/admin/login'
                && this.$route.path != '/admin/agentImprove'
                && this.$route.path != '/order/login') {
                let that = this;
                let gwm = require('gwm');
                gwm.creation({
                    'txt': that.$store.state.user.name,
                    'container': '.el-table', //#gwm
                    'fontSize': 40
                })
            }
        },
        searchMethods(params, no_search) {
            this.sort_params = {}
            this.current_page = 1
            this.per_page = 25
            this.search_end = false
            this.$nextTick(() => {
                this.search_end = true
            })
            this.search_params = params
            if (!no_search) {
                this.getTableData()
            }
        },
        async getMyinfo () {
            let myInfo = await getMyInfo(this.$axios);
            if (myInfo.data.status == 'success') {
                this.$store.commit("setRoleInfo",myInfo.data.data)
                this.$store.commit("setUser",myInfo.data.data);
            }
        },
        refreshData() {
            this.showAuditoRecording = false
            this.getTableData()
        },
        agentAnwser(data) {
            this.$refs['agent-anwser'].showOn(data, 'teacher')
        },
        auditorOrder(val) {
            this.dialogFormVisible = true;
            this.order = val.id;
            if (val.statuss[0].id == 5 || val.statuss[0].id == 15) {
                this.qualityFailed = true
            } else {
                this.qualityFailed = false
            }
        },
        showAudito(data, index) {
            this.showAuditoRecording = true;
            data.opinions.forEach(v => {
                v.from = '审核员'
                v.time_code = Date.parse(new Date(v.created_at))
            })
            data.teacher_opinions.forEach(v => {
                v.from = ''
                v.time_code = Date.parse(new Date(v.created_at))
            })
            this.teacher_opinions = data.opinions.concat(data.teacher_opinions);
            this.teacher_opinions.sort((a, b) => a.time_code < b.time_code ? 1 : -1)
            if (data.noRead > 0) {
                this.readAuditor(this.teacher_opinions, index)
            }
        },
        readAuditor(data, index) {
            let ids = []
            data.forEach(v => {
                ids.push(v.id)
            });
            this.$axios.put('/api/opinion/update_read_status', {
                ids: ids
            }).then(res => {
                if (res.data.code == 200) {
                    this.tableData[index].noRead = 0
                } else {
                    this.$message({
                        type: 'error',
                        message: res.data.message
                    })
                }
            })
        },
        getTableData() {
            let params = {
                perPage: this.per_page,
                page: this.current_page,

            }
            params = {...params, ...this.search_params, ...this.sort_params}
            this.loading = true
            this.$axios.get('api/order/teacher_auditor', {
                params: params
            }).then(res => {
                if (res.data.code == 200) {
                    let data = res.data.data
                    this.total = res.data.page.total
                    this.tableData = data
                    this.tableData.forEach(v => {
                        if (v.student_review_file) {
                            v.fileArr = v.student_review_file.split('&')
                        }
                        let status = v.statuss
                        v.can_click = true
                        if (status[0].id == 15) {
                            return v.can_click = true
                        } else {
                            if (status.findIndex(v => v.id == 17) > -1) {
                                return v.can_click = false
                            }
                        }

                        let index = status.findIndex(v => v.id == 16),
                            index1 = status.findIndex(v => v.id == 18);
                        if (index1 != -1 && index > index1) {
                            v.can_click = false
                        }
                    })
            } else {
                    this.$message({
                        type: 'error',
                        message: res.data.message
                    })
                }
            }).catch(e => {
                return new Error(e)
            }).finally(() => {
                this.loading = false
            })
        },
        tableSort(column) {
            let params = {
                sort_str: column.prop,
            }
            if (column.order == 'ascending') {
                params.sort_order = 'asc'
            } else if (column.order == 'descending') {
                params.sort_order = 'desc'
            } else {
                params = {}
            }
            this.sort_params = params
            this.getTableData()
        },
        headerSet(data) {
            if(data.every(v => v.is_show == false)) {
                this.checked99 = false
            }
            if (data.some(v => v.is_show == true)) {
                this.checked99 = true
            }
            this.table_show = false
            this.loading = true
            this.tableHeader = data
            this.$nextTick(() => {
                this.table_show = true
                this.loading = false
            })
            setTimeout(() => {
                this.$nextTick(() => {
                    this.gwm()
                })
            }, 300)
        },
        getAuditorDate(itemData) {
            let statuss = itemData.statuss
            let createDay= ''
            if(statuss[statuss.findIndex(v => v.id == 16)]) {
                createDay = statuss[statuss.findIndex(v => v.id == 16)].pivot.created_at;
            }

            //获取接单的时间戳
            createDay = createDay.replace(/-/g, "/");
            var createTime = new Date(createDay).getTime();
            //获取当前的时间戳
            var nowTime = new Date().getTime();
            //获取处理时间戳
            let cha = nowTime - createTime;
            //转换天数
            let round2 = (cha / 1000 / 60 / 60 / 24).toFixed(2)
            let	processingTime = (Math.ceil(round2 * 10) / 10).toFixed(1)
            if (processingTime < 0) {
                return '0.0'
            }  else if (processingTime < 0.1) {
                return '0.1'
            } else {
                return processingTime;
            }
        },
        pageChange(data) {
            this.per_page = data.perPage
            this.current_page = data.page
            this.getTableData()
        },
        showAuditRecord() {
            this.form = {}
        },
        submitForm(formName, pass) {
            this.$refs[formName].validate(valid => {
                if (valid) {
                    let obj = {
                        pass: pass,
                        review: this.form.review
                    }
                    if (this.form.review == '' && pass == 'yes') {
                        obj.review = '过'
                    }
                    if (this.form.review == '' && pass == 'no') {
                        this.$message({
                            type: 'warning',
                            message: '请输入审核意见'
                        })
                        return
                    }
                    this.$axios.put(`/api/order/${this.order}/teacher_audit`, obj).then(({data}) => {
                        if (data.status == "success") {
                            this.$message.success("操作成功");
                            this.dialogFormVisible = false;
                            this.getTableData()
                            this.getMyinfo()
                        } else {
                            this.$message.error(data.message);
                        }

                    })
                    .catch(err => {
                        this.$message.error(err)
                    })
                } else {
                    return false;
                }
            });
        },
        resetForm(formName) {
            this.$refs[formName].resetFields();
        },
    }
}
</script>

<style lang="less" scoped>
/deep/.el-table {
    .file_sh {
		font-size: 25px;
		margin-right: 10px;
	}
}
.flex-line {
    display: flex;
    .title {
        text-align: justify;
        text-align-last: justify;
        flex: 0 0 80px;
    }
    .content {
        flex: 1;
        .time {
            float: right;
            margin-left: 20px;
            color: #909399;
            font-weight: normal;
            font-size: 14px;
        }
    }
}
</style>
